<template>
  <div>
    <xy-table
      :api="api"
      :columns="columns"
      v-show="!showDetail"
    >
      <template #addItem>
        <el-button
          @click="addItem"
          size="mini"
        >
          <i class="el-icon-plus"></i>
          {{ $language.local("添加") }}
        </el-button>
      </template>
      <template #operationButton="{ scope }">
        <ul class="operation-btn row jcsa">
          <template v-if="scope.row.checkstatus !== 1">
            <li>
              <el-tooltip
                :content="$language.local('修改')"
                :enterable="false"
                class="item"
                effect="dark"
                placement="top"
              >
                <el-button
                  @click="onEdit(scope.row)"
                  circle
                  icon="el-icon-edit"
                  size="mini"
                  type="primary"
                ></el-button>
              </el-tooltip>
            </li>
            <li>
              <el-tooltip
                :content="$language.local('删除')"
                :enterable="false"
                class="item"
                effect="dark"
                placement="top"
              >
                <el-button
                  @click="deleteItem(scope.row)"
                  circle
                  icon="el-icon-delete"
                  size="mini"
                  type="danger"
                ></el-button>
              </el-tooltip>
            </li>
            <li v-if="user.roletype === 99">
              <el-tooltip
                :content="$language.local('审核')"
                :enterable="false"
                class="item"
                effect="dark"
                placement="top"
              >
                <el-button
                  @click="onCheck(scope.row)"
                  circle
                  icon="el-icon-s-check"
                  size="mini"
                  type="warning"
                ></el-button>
              </el-tooltip>
            </li>
          </template>
          <template v-else>
            <li>
              <el-tooltip
                :content="$language.local('发布')"
                :enterable="false"
                class="item"
                effect="dark"
                placement="top"
              >
                <el-button
                  @click="onPay(scope.row)"
                  circle
                  icon="el-icon-check"
                  size="mini"
                  type="primary"
                ></el-button>
              </el-tooltip>
            </li>
            <li>
              <el-tooltip
                :content="$language.local('结算')"
                :enterable="false"
                class="item"
                effect="dark"
                placement="top"
              >
                <el-button
                  @click="showSettlementTaskDialog(scope.row)"
                  circle
                  icon="el-icon-finished"
                  size="mini"
                  type="primary"
                ></el-button>
              </el-tooltip>
            </li>
            <li>
              <el-tooltip
                :content="$language.local('开发票')"
                :enterable="false"
                class="item"
                effect="dark"
                placement="top"
              >
                <el-button
                  @click="$router.replace({ path: 'invoice_apply' })"
                  circle
                  icon="el-icon-takeaway-box"
                  size="mini"
                  type="primary"
                ></el-button>
              </el-tooltip>
            </li>
          </template>
        </ul>
      </template>
      <el-table-column
        :label="$language.local('TskStatus')"
        align="center"
        prop="TskStatus"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.TskStatus === 1">
            <i class="el-icon-circle-check green"></i>
            已审核
          </span>
          <span v-else-if="scope.row.TskStatus === 2">已发包</span>
          <span v-else-if="scope.row.TskStatus === 3">已充值</span>
          <span v-else-if="scope.row.TskStatus === 4">已结算</span>
          <span v-else-if="scope.row.TskStatus === 5">已开票</span>
          <span v-else>
            <i class="el-icon-circle-close red"></i>
            草稿待审核
          </span>
        </template>
      </el-table-column>
    </xy-table>
    <div
      class="detail"
      v-show="showDetail"
    >
      <el-form
        :disabled="isCheck"
        :model="formData"
        :rules="$rules"
        class="pr-2 pl-2 grid-flex"
        label-width="7rem"
        ref="taskInfoRef"
        status-icon
      >
        <el-form-item
          :label="$language.local('customerName')"
          prop="MID"
        >
          <select-merchantid v-model="formData.MID"></select-merchantid>
        </el-form-item>
        <el-form-item
          :label="$language.local('任务类型')"
          prop="ServiceType"
        >
          <select-servicetype
            :merchantId="formData.MID"
            no-data-text="请先选择企业"
            v-model="formData.ServiceType"
          ></select-servicetype>
        </el-form-item>

        <el-form-item
          :label="$language.local('项目名称')"
          prop="projectName"
        >
          <xy-input
            clearable
            v-model="formData.projectName"
          ></xy-input>
        </el-form-item>
        <el-form-item
          :label="$language.local('Amount')"
          prop="Amount"
        >
          <xy-decimal v-model="formData.Amount"></xy-decimal>
        </el-form-item>
        <el-form-item
          :label="$language.local('开始日期')"
          prop="BegTime"
        >
          <select-date v-model="formData.BegTime"></select-date>
        </el-form-item>
        <el-form-item
          :label="$language.local('结束日期')"
          :rules="EndTimeRule"
          prop="EndTime"
        >
          <select-date v-model="formData.EndTime"></select-date>
        </el-form-item>

        <el-form-item
          :label="$language.local('SettlementModes')"
          prop="SettlementModes"
        >
          <el-select
            clearable
            filterable
            v-model="formData.SettlementModes"
          >
            <el-option
              :key="key"
              :label="value"
              :value="value"
              v-for="(value, key) in settlementModes"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="otherSettlementModes"
          v-if="formData.SettlementModes == 4"
        >
          <xy-input v-model="formData.otherSettlementModes"></xy-input>
        </el-form-item>

        <el-form-item v-if="ServiceContents.length > 0">
          <el-select
            @change="ServiceContentChange"
            class="select-servicecontent"
            placeholder="可选择参考范例"
            v-model="ServiceContent"
          >
            <el-option
              :key="item.Id"
              :label="item.ModelTitle"
              :value="item"
              v-for="item in ServiceContents"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          :label="$language.local('工作内容')"
          class="textarea"
          prop="WorkContent"
        >
          <xy-input
            :autosize="{ minRows: 3 }"
            clearable
            type="textarea"
            v-model="formData.WorkContent"
          ></xy-input>
          <div class="tips">
            1、工作内容的描述不能有如下字眼：
            <em class="red">工资、补贴、津贴、福利、劳务、销售、经纪、工程安装、装修、装饰、清包工</em>等字眼；
          </div>
          <div class="tips">2、工作内容描述不录入具体人员姓名、金额数字等详细内容；</div>
        </el-form-item>
        <el-form-item
          :label="$language.local('RecruitmentRequirements')"
          class="textarea"
          prop="RecruitmentRequirements"
        >
          <xy-input
            :autosize="{ minRows: 3 }"
            clearable
            type="textarea"
            v-model="formData.RecruitmentRequirements"
          ></xy-input>
        </el-form-item>

        <el-form-item
          class="textarea"
          label="邀请"
        >
          <span
            class="gray"
          >本平台根据任务完成率,好评率为您推荐下列等待接单的明星签约自由职业工作者,可尽快开始任务,您也可以使用批量导入功能邀请其它自由工作者,待工作者签约完成后,即可开始任务。您还可以忽略此项，等待其它自由工作者报名后由您进行审核再开始任务。</span>
        </el-form-item>
      </el-form>
      <div class="row jcc">
        <el-transfer
          :data="employees"
          :format="{
            noChecked: '${total}',
            hasChecked: '${checked}/${total}',
          }"
          :props="{
            key: 'Id',
            label: 'EmpName',
          }"
          :right-default-checked="orderRightEmployees"
          :titles="['邀请自由职业工作者', '已邀请']"
          filter-placeholder="按灵工姓名搜索"
          filterable
          style="text-align: left; display: inline-block"
          v-model="formData.EmployeeList"
        >
          <div
            class="row aic"
            slot-scope="{ option }"
          >
            {{ option.EmpName }}
            <el-rate
              :value="getRate(option.Id)"
              disabled
              score-template="{value}"
              show-score
              style="margin-top: 5px"
              text-color="#ff9900"
              v-if="option.zt"
            ></el-rate>
          </div>
          <div
            class="upload-btn row jcc aic"
            slot="right-footer"
          >
            <!-- <el-button class="transfer-footer" size="small"> 操作 </el-button> -->
            <upload-file
              :name="formData.attFileName"
              :on-success="onSuccess"
              :show-file-list="false"
              v-model="formData.attFilePath"
            >
              <el-button
                class="transfer-footer"
                type="primary"
              >批量导入灵工</el-button>
              <template #tip>
                <span></span>
              </template>
            </upload-file>
          </div>
        </el-transfer>
      </div>
      <div class="form-footer mt-2 pb-3">
        <el-button
          @click="showDetail = false"
          size="mini"
        >
          {{
          $language.local("返回")
          }}
        </el-button>
        <template v-if="isCheck">
          <el-button
            @click="showReasonDialog"
            class
            size="mini"
            type="danger"
          >{{ $language.local("不通过") }}</el-button>
          <el-button
            @click="onCheck(1)"
            size="mini"
            type="success"
          >
            {{
            $language.local("通过")
            }}
          </el-button>

          <!-- #region 审核原因 -->
          <el-dialog
            :title="$language.local('Reason')"
            :visible.sync="inputReasonVisible"
          >
            <el-form
              :model="formData"
              :rules="$rules"
              ref="ReasonRef"
              status-icon
            >
              <el-form-item prop="Reason">
                <xy-input
                  clearable
                  v-model="formData.Reason"
                ></xy-input>
              </el-form-item>
            </el-form>
            <div
              class="dialog-footer"
              slot="footer"
            >
              <el-button
                @click="onCheck(2)"
                type="primary"
              >确 定</el-button>
            </div>
          </el-dialog>
          <!-- #endregion -->
        </template>
        <el-button
          @click="onSubmit('taskInfoRef')"
          size="mini"
          type="primary"
          v-else
        >{{ $language.local("确定") }}</el-button>
      </div>
    </div>
    <el-dialog
      :title="dialogData.title"
      :visible.sync="formDialogVisible"
      width="62%"
    >
      <div class="amount-box">
        金额:
        <span class="symbol">￥</span>
        <span class="amount-num red">{{ addForm.Amount }}</span>
      </div>
      <ul class="grid-flex">
        <template v-for="(value, key) in formData">
          <template v-if="/MID/i.test(key)"></template>
          <template v-else-if="key === 'SettlementModes'">
            <li
              :key="key"
              class="settlement-mode"
            >
              <div class="label font-justify">{{ $language.local(key) }}：</div>
              <div class="value">{{ settlementModes[addForm[key]] }}</div>
            </li>
          </template>
          <li
            :key="key"
            class="row"
            v-else
          >
            <div class="label font-justify">{{ $language.local(key) }}：</div>

            <div class="value">{{ addForm[key] }}</div>
          </li>
        </template>

        <li class="li-html column">
          <div class="label font-justify">{{ $language.local("WorkContent") }}：</div>
          <div
            class="html-text m-1"
            v-html="addForm.WorkContent"
          ></div>
        </li>
        <li class="li-html column">
          <div class="label font-justify">{{ $language.local("RecruitmentRequirements") }}：</div>
          <div
            class="html-text m-1"
            v-html="addForm.RecruitmentRequirements"
          ></div>
        </li>
      </ul>
      <div class="form-footer">
        <el-button
          @click="formDialogVisible = false"
          class="mr-1"
          icon="el-icon-close"
          size="mini"
        >取消</el-button>
        <el-button
          @click="onPay"
          class="ml-1"
          icon="el-icon-finished"
          size="mini"
          type="danger"
        >付款</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import API from "../../plugins/api";

export default {
  inject: ["reload"],
  data() {
    const validateEndTime = (rule, value, callback) => {
      if (!this.formData.BegTime) {
        callback(new Error("请输入开始时间！"));
        return;
      }
      const begTime = new Date(this.formData.BegTime);
      const endTime = new Date(value);
      if (endTime.compare(begTime)) {
        callback();
      } else {
        callback(new Error("请输入大于开始时间的日期！"));
      }
    };
    return {
      showDetail: false,
      isCheck: false,
      apiName: "/api/Seivice",
      api: new API("/api/ServiceProject/"),
      formDialogVisible: false,
      dialogData: {
        title: "",
      },
      columns: {
        customerName: "",
        projectName: "",
        //  PerformanceFeeSettlementRules: "",
        ServiceType: "",
        // WorkContent: "",
        // ServiceName: "",
        BegTime: "",
        EndTime: "",
        Amount: "",
        // Ctime: "",
        checkstatus: "",
      },

      formData: {
        customerName: null,
        SID: "",
        BusinessNo: "",
        ServiceType: "",
        // PostName: "",
        projectName: "",

        recruitPerson: "",

        // WorkContent: "",
        // PerformanceFeeSettlementRules: "",
        // RecruitmentRequirements: "",

        // ServiceName: "",

        BegTime: "",
        EndTime: "",
        SettlementModes: "",
        // EmployeeList: [],
        // otherSettlementModes: "",
        // checker: "",
        // checkstatus: "",

        // Reason: "",
      },
      addDialogVisible: false,
      addForm: {},
      rechargeData: {
        ServiceProviderName: "",
        ServiceBank: "",
        // ServiceBankId: null,
        ServiceAccountNo: "",
        PayChannelId: "",

        // MID: "客户",
        CustomerName: "",
        // _agentname: "客户名称",
        ruleType: "",
        RechargeRate: "",
        RechargeTime: "",
        RechargeAmount: "",
        // _rechargetime: "充值时间",
        AccountAmount: "",
        PayingAccountName: "",
        PayingBank: "",
        PayingAccount: "",
        Note: "",
      },
      emprate: 3.7,
      list: null,
      customers: [],
      services: [],
      settlementModes: {
        1: "按项目工作时间多次结算",
        2: "按项目工作成果一次结算",
        3: "按项目完工进度多次结算",
        4: "其它方式",
      },
      EndTimeRule: [
        { required: true, message: "不能为空", trigger: "blur" },
        { validator: validateEndTime, trigger: "blur" },
      ],
      ServiceContents: [],
      orderEmployees: [],
      orderRightEmployees: [1, 2],
      employees: [
        {
          Id: 1794,
          EmpName: "张诚信",
          desc: "备选项",
        },
      ],

      props: {
        key: "Id",
        label: "EmpName",
      },
      settlementTaskDlgVisible: false,
      user: this.$store.getters.user,
    };
  },
  watch: {
    "formData.ServiceType": {
      async handler(newValue) {
        const response = await this.$http.get(
          `/api/ServiceProject/GetContentModel?ServiceContent=${newValue}`
        );
        console.log(response.data.Data);
        if (response.data.Data) {
          this.ServiceContents = response.data.Data;
        }
      },
    },
  },
  created() {
    this.getEemloyee();
  },
  methods: {
    async getEemloyee() {
      const response = await this.$http.get(
        "/api/employee/GetList?auditStatus=1"
      );
      console.log(response);
      this.employees = response.data.Data;
    },
    handleChange(...args) {
      console.log(args);
    },
    addItem() {
      // this.$router.push("/task-detail");
      this.showDetail = !this.showDetail;
    },
    onEdit(row) {
      this.$router.push({
        path: "/task-info",
        query: {
          action: "Edit",
          apiName: "/api/ServiceProject/Edit",
          id: row.ID,
        },
      });
    },
    onCheck(row) {
      this.$router.push({
        path: "/task-info",
        query: {
          action: "Check",
          apiName: "/api/ServiceProject/Check/",
          id: row.ID,
        },
      });
    },
    async getCustomer() {
      let response = await this.$http.get("/api/Merchant/GetList");
      this.customers = response.data.Data;
    },
    async getServices() {
      let response = await this.$http.get("/api/ServiceProvider/GetList");
      this.services = response.data.Data;
    },

    async deleteItem(row) {
      let res = await this.$confirm(`此操作将会删除该行，是否继续?`, "提示", {
        type: "warning",
        confirmButtonText: this.$language.local("是"),
        cancelButtonText: this.$language.local("否"),
      }).catch(() => {
        this.$message.info("Has been cancelled");
      });
      if (res != "confirm") {
        return;
      }
      let response = await this.$http.delete(
        `/api/ServiceProject/Delete/${row.ID}`
      );
      if (response.data.Code != 200) {
        this.$message.error(response.data.Message);
        return;
      }
      this.$message.success("删除成功");
      this.reload();
    },
    onPay(row) {
      console.log(row);
      this.dialogData.title = "发布任务";
      this.addForm = row;
      this.formDialogVisible = true;
    },
    async onSuccess(e) {
      console.log(e);
      this.formData.attFileName = e.docname;
      const response = await this.$http.post(
        `/api/TSKSettlement/batchInput?ExcelUrl=${e.docurl}`
      );
      console.log(response);
      this.employees = [...this.employees, ...response.data.Data];
      console.log(this.employees);
      response.data.Data.forEach((v) => {
        this.orderEmployees.push(v.Id);
      });
      // console.log(this.orderEmployees);
      // this.orderEmployees
    },
    getRate(id) {
      let int = id % 10;
      let decimal = 4 + int / 10;
      return decimal;
    },
    showSettlementTaskDialog(row) {
      this.$router.push({
        path: "TSKSettlementDetail",
        query: {
          id: row.ID,
        },
      });
    },

    async onSubmit(formName) {
      console.log(this.employees);
      console.log(this.formData);
      await this.$refs[formName].validate();
    },
  },
};
</script>

<style lang="less" scoped>
.el-select {
  width: 100%;
}
.el-date-picker {
  width: 100%;
}

.operation-btn {
  width: 100%;
  display: flex;
  justify-content: space-around;
}

.el-dialog {
  .amount-box {
    width: 100%;
    text-align: center;
    font-size: 2rem;
    margin-bottom: 2rem;
    .symbol {
      font-size: 0.8rem;
    }
    .amount-num {
      font-size: 3rem;
    }
  }
  ul {
    display: flex;
    width: 100%;
    li {
      width: 50%;
      display: flex;
      justify-content: space-between;
      padding: 1ex 2rem;
      text-align: left;
      .label {
        width: 100px;
      }
      .value {
        text-align: right !important;
      }
      &.settlement-mode {
        width: 50%;
      }
    }
    .li-html {
      width: 100%;

      .html-text {
        width: 100%;
      }
    }
  }
}

.upload-btn {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.tips {
  font-size: 13px;
  color: gray;
}
</style>
